package com.twinkle.controller;

import com.alibaba.fastjson.JSONObject;
import com.twinkle.model.PreviewDataResultUI;
import com.twinkle.model.MetadataColumnEntity;
import com.twinkle.model.ProcessResult;
import com.twinkle.service.PreviewDataResultService;
import com.twinkle.service.impl.MetadataColumnServiceImpl;
import com.twinkle.utils.ShellUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;


/**
 * @title: PreviewDataController
 * @description: 数据预览接口类
 * @author: Paul
 * @date: 2023/3/16 11:40
 */
@Controller
@RequestMapping("/algo/previewdata")
public class PreviewDataController {

    @Autowired
    PreviewDataResultService previewDataResultService;
    @Autowired
    MetadataColumnServiceImpl metadataColumnService;
    @Value("${data.algo.path}")
    private String algoPath;

    @RequestMapping("/addpage")
    public String addKmeansModelPage(Model model, @Param("dataSourceId") int dataSourceId, @Param("tableName") String tableName){
        JSONObject param = new JSONObject();
        //生成模型id
        String modelId = System.currentTimeMillis()+"";
        param.put("id", modelId);
        param.put("appName", "preview_data");
        param.put("dataSourceId", dataSourceId);
        param.put("tableName", tableName);
        //获取列集合
        List<MetadataColumnEntity> tableColumns = metadataColumnService.getTableColumns(dataSourceId, tableName);
        List<String> colList = new ArrayList<>();
        for (MetadataColumnEntity metadataColumnEntity : tableColumns) {
            colList.add(metadataColumnEntity.getColumnName());
        }
//        param.put("trainCols", colList);
        model.addAttribute("colList", colList);
        param.put("trainCols", JSONObject.toJSON(colList));
        //保存模型参数
        System.out.println(JSONObject.toJSONString(param));
        //调用聚类算法
        String shell = "python " + algoPath + "pre_data_process/preview_data.py \"" + JSONObject.toJSONString(param).replaceAll("\"", "\\\\\"") + "\"";
        System.out.println(shell);
        ProcessResult processResult = ShellUtil.execShell(shell);
        System.out.println("processResult : " + JSONObject.toJSONString(processResult));
        PreviewDataResultUI previewDataResult = previewDataResultService.getPreviewDataResultByModelId(modelId);
        System.out.println(JSONObject.toJSONString(previewDataResult));
        model.addAttribute("previewDataResult", previewDataResult);
        return "algo_plat/preview_data/predata";
    }

}
